from datetime import datetime, timedelta
from aiogram import Router, F
from aiogram.types import Message
from keyboards.set_menu import just_keyboard, cancel_keyboard_report, report_keyboard, report_keyboard_weekly

from db.PGConnector import PGFamily, PGUser, PGPurchase
from .utils import try_except_decorator
from datetime import datetime, timedelta

router = Router()

def get_expences_string(dict):
    result_string = ''

    for name, amount in dict.items():
        if name == "ИТОГ":
            result_string += f"{name}: {amount} руб\n\n"
        else:
            result_string += f"@{name}: {amount} руб\n\n"
    
    return result_string

def get_expences_string_weekly(data):
    formatted_strings = [f"\n\n{date}\n🏪{name}\n💵{amount} руб\n\n---------------------------------" for date, amount, name in data]
    result = ''.join(formatted_strings)
    
    return result

@try_except_decorator
@router.message(F.text == "Отчет")
async def get_expenses(message: Message):
    await message.answer(text="Выберете тип отчета:", reply_markup=report_keyboard())

@try_except_decorator
@router.message(F.text == "Назад")
async def get_expenses(message: Message):
    await message.answer(text="Выберете тип отчета:", reply_markup=report_keyboard())

@try_except_decorator
@router.message(F.text == "Все расходы")
async def get_expenses(message: Message):
    user_id = message.chat.id
    pg_purchase = PGPurchase()
    expenses = pg_purchase.get_info_expenses(user_id)
    
    if not expenses:
        await message.answer(f"Пока вы не совершали покупок. Все еще впереди 🤑", reply_markup=report_keyboard())
    else:
        await message.answer(f"Информация о расходах за последние 30 дней:\n\n{get_expences_string(expenses)}",
                             reply_markup=report_keyboard())

def generate_past_weeks():
    today_date = datetime.now()
    end_date = today_date
    weeks_list = []

    for i in range(1, 5):
        start_date = end_date - timedelta(days=6)
        week_str = f"Неделя {i} ({start_date.strftime('%d.%m')} - {end_date.strftime('%d.%m')})"
        weeks_list.append(week_str)
        end_date = start_date - timedelta(days=1)
    
    return weeks_list

weeks = generate_past_weeks()
weeks.sort()


@try_except_decorator
@router.message(F.text == "Ваши покупки за неделю")
async def get_expenses(message: Message):
    await message.answer(text='Отчет за последние 7 дней', reply_markup=report_keyboard_weekly())

@try_except_decorator
@router.message(F.text == weeks[0])
async def get_expenses(message: Message):
    user_id = message.chat.id
    pg_purchase = PGPurchase()
    expenses = pg_purchase.get_info_weeks_expenses(1, user_id)
    
    if not expenses:
        await message.answer(f"Пока вы не совершали покупок. Все еще впереди 🤑", reply_markup=report_keyboard_weekly())
    else:
        await message.answer(f"{get_expences_string_weekly(expenses)}", reply_markup=report_keyboard_weekly())

@try_except_decorator
@router.message(F.text == weeks[1])
async def get_expenses(message: Message):
    user_id = message.chat.id
    pg_purchase = PGPurchase()
    expenses = pg_purchase.get_info_weeks_expenses(2, user_id)

    if not expenses:
        await message.answer(f"Пока вы не совершали покупок. Все еще впереди 🤑", reply_markup=report_keyboard_weekly())
    else:
        await message.answer(f"{get_expences_string_weekly(expenses)}", reply_markup=report_keyboard_weekly())

@try_except_decorator
@router.message(F.text == weeks[2])
async def get_expenses(message: Message):
    user_id = message.chat.id
    pg_purchase = PGPurchase()
    expenses = pg_purchase.get_info_weeks_expenses(3, user_id)
    
    if not expenses:
        await message.answer(f"Пока вы не совершали покупок. Все еще впереди 🤑", reply_markup=report_keyboard_weekly())
    else:
        await message.answer(f"{get_expences_string_weekly(expenses)}", reply_markup=report_keyboard_weekly())

@try_except_decorator
@router.message(F.text == weeks[3])
async def get_expenses(message: Message):
    user_id = message.chat.id
    pg_purchase = PGPurchase()
    expenses = pg_purchase.get_info_weeks_expenses(4, user_id)
    
    if not expenses:
        await message.answer(f"Пока вы не совершали покупок. Все еще впереди 🤑", reply_markup=report_keyboard_weekly())
    else:
        await message.answer(f"{get_expences_string_weekly(expenses)}", reply_markup=report_keyboard_weekly())



